package org.anarcoding.twitterbot.view;

import java.util.ArrayList;
import java.util.List;

import org.anarcoding.twitterbot.model.AnarcoTwitterBot;
import org.anarcoding.twitterbot.model.AnarcoTwitterBotConf;
import org.anarcoding.twitterbot.model.AnarcoTwitterException;
import org.anarcoding.twitterbot.providers.AnarcoTwitterDialogProvider;
import org.anarcoding.twitterbot.providers.AnarcoTwitterModelProvider;
import org.anarcoding.twitterbot.services.IAnarcoTwitterServicesImplBuilder;
import org.eclipse.jface.viewers.TableViewer;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;

import com.anarcoding.util.SWTUtil;

public class ShlAnarcoTwitterPrincipalControl {
	private CmpAnarcoTwitterPrincipal	compositePrincipal;

	private List< AnarcoTwitterBot >	lista;
	private TableViewer					tblVwr;

	public ShlAnarcoTwitterPrincipalControl( CmpAnarcoTwitterPrincipal compo ) {
		compositePrincipal = compo;

		lista = new ArrayList< AnarcoTwitterBot >();

		try {
			for( AnarcoTwitterBotConf conf : AnarcoTwitterModelProvider.getListaDeConfiguraciones() ) {
				try {
					AnarcoTwitterBot nvoBot = new AnarcoTwitterBot();
					nvoBot.setAnarcoTwitterServices( IAnarcoTwitterServicesImplBuilder.build( conf ) );
					lista.add( nvoBot );
				} catch( AnarcoTwitterException e ) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		} catch( AnarcoTwitterException e ) {
			e.printStackTrace();
		}

		AnarcoTwitterPrincipalTableConfig tblConfig = new AnarcoTwitterPrincipalTableConfig();

		tblVwr = new TableViewer( compositePrincipal.getTable() );
		tblVwr.setContentProvider( tblConfig );
		tblVwr.setLabelProvider( tblConfig );
		tblVwr.setInput( lista );
		tblVwr.refresh();

		addControls();
	}

	private void addControls() {

		compositePrincipal.getBtnNuevoBot().addSelectionListener( new SelectionAdapter() {
			public void widgetSelected( SelectionEvent e ) {

				AnarcoTwitterBotConf nvaConf = AnarcoTwitterDialogProvider.getAnarcoTwitterBotConfFromDialog( compositePrincipal.getShell() );

				try {
					AnarcoTwitterBot nvoBot = new AnarcoTwitterBot();
					nvoBot.setAnarcoTwitterServices( IAnarcoTwitterServicesImplBuilder.build( nvaConf ) );
					lista.add( nvoBot );
					tblVwr.refresh();
				} catch( AnarcoTwitterException e1 ) {
					SWTUtil.openDialog( compositePrincipal.getShell(), "Error", "" + e1.getMessage(), SWT.ICON_ERROR );
					e1.printStackTrace();
				}

			}
		} );

	}

	public CmpAnarcoTwitterPrincipal getCompositePrincipal() {
		return compositePrincipal;
	}

	public void setCompositePrincipal( CmpAnarcoTwitterPrincipal compositePrincipal ) {
		this.compositePrincipal = compositePrincipal;
	}

}
